﻿//学生参加考试
$(function () {

    //是否结束
    var flag = false;
    countTime();
    // 绑定提交按钮
    $("#submit-btn").click(submit);
    //监听窗口关闭或刷新事件，如果还没有做完，给用户一个提示
    $(window).unbind('onbeforeunload');
    window.onbeforeunload = function () {
        if (!flag) {
            var e = window.event||e;
            e.returnValue = "考试尚未结束，您确定离开?";
        }
    };

    /**
     * 计时函数
     */
    function countTime() {
        //用于显示倒计时的div
        var $showTime = $("#count-time");
        //获取考试时长
        var limit = $("#time-limit").val(),
            //分钟数
            minutes = parseInt(limit),
            //秒数（第一位）
            mf = 0,
            //秒数（第二位）
            ms = 0;
        var timer = setInterval(function () {
            if (ms > 0) {
                --ms;
                _setTime();
            } else if (mf > 0) {
                ms = 9;
                --mf;
                _setTime();
            } else if (minutes > 0) {
                mf = 5;
                ms = 9;
                --minutes;
                _setTime();
            } else {
                flag = true;
                //计时结束
                clearInterval(timer);
                layer.msg("时间已到，系统正在交卷...");
                //自动交卷
                submit();
            }
        }, 1000);//1000毫秒 = 1秒

        //设置时间
        function _setTime() {
            $showTime.html(minutes + ":" + mf + ms);
        }
    }

    /**
     * 交卷
     * 提交的json串的格式:
     * {
	 * 		eid: 1,//试卷id
	 * 		questions:[
	 * 			{id: 2, answer: "1,2"}	
	 * 		]
	 * }
     */
    function submit() {
        var basePath = $("#context-path").val();
        var result = {};//object
        //将试卷ID放入result对象中
        result.examId = $("#exam-id").val();
        //result.examId = 1;
        result.singles = [];
        result.multis = [];
        result.judges = [];
        //处理单选题
        $("#single-container").find("div.question").each(function (index, question){
            //获取每道题div对象
            var $question = $(question);
            var id = $question.find("input[name=question-id]").val();//题目的ID
            var rightAnswer = $question.find("input[name=right-answer]").val();//正确答案
            var score = $question.find("input[name=question-score]").val();//分数
            //找到所有被选中的radio
            var $checkeds = $question.find("input:checked");
            var answer = $checkeds.length > 0 ? $checkeds.val() : "";//三元表达式
            result.singles.push({
                id: id,//题目ID
                type: 1,//题目类型
                answer: answer,
                rightAnswer:rightAnswer,
                score:score
            });
        });
        //处理多选题
        $("#multi-container").find("div.question").each(function (index, question) {
            $question = $(question);
            var id = $question.find("input[name=question-id]").val();
            var rightAnswer = $question.find("input[name=right-answer]").val();//正确答案
            var score = $question.find("input[name=question-score]").val();//分数
            //拼接答案串
            var answer = "";
            //遍历被选中的选项
            $question.find("input:checked").each(function () {
                answer += (this.value + ",");
            });//A,B,C,
            result.multis.push({
                id: id,
                type: 2,
                answer: answer.substring(0, answer.length - 1),//截掉最后一个逗号
                rightAnswer:rightAnswer,
                score:score
            });
        });
        //处理判断题
        $("#judge-container").find("div.question").each(function (index, question) {
            $question = $(question);
            id = $question.find("input[name=question-id]").val();
            var rightAnswer = $question.find("input[name=right-answer]").val();//正确答案
            var score = $question.find("input[name=question-score]").val();//分数
            $checkeds = $question.find("input:checked");
            answer = $checkeds.length > 0 ? $checkeds.val() : "";
            result.judges.push({
                id: id,
                type: 3,
                answer: answer,
                rightAnswer:rightAnswer,
                score:score
            });
        });
        //ajax请求（post方式的请求）
        console.log(JSON.stringify(result));
        $.post(
                basePath+"/examPaperSubmit.me",
        		"result=" + JSON.stringify(result), 
        		function (data) {
		            if (data.code === 0) {
		            	layer.alert(data.msg,function(){
                            //关闭当前窗口
                            /*window.opener=null;
                            window.open('','_self');
                            window.close();*/
                            window.location.href = basePath+"/index.i";
                        });
		            }else {
		            	layer.alert(data.msg);
		            }
        }, "json");

    }

});